import { useEffect, useState } from 'react'
import type { ChangeEvent } from 'react'

type FormData = {
  [key: string]: any
}

interface DataFetcher<T> {
  (args: T & { pageNumber: number; pageSize: number }): Promise<any>
}

// 自定义hook，将重复的代码抽取出来，封装成一个hook，方便复用
// 泛型写法
const useDataList = <U, T extends FormData>(initialFormData: T, fetData: DataFetcher<T>) => {
  const [loading, setLoading] = useState<boolean>(false)
  const [dataList, setDataList] = useState<Array<U>>([])
  const [pageNumber, setPageNumber] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)
  const [queryParam, setQueryParam] = useState<T>(initialFormData)

  const loadData = async (pageNumber: number, pageSize: number) => {
    setLoading(true)
    await fetData({ pageNumber, pageSize, ...queryParam })
      .then(({ data: { list, total } }) => {
        setDataList(list)
        setTotal(total)
      })
      .catch((error) => {
        console.log(error)
      })
      .finally(() => {
        setLoading(false)
      })
  }
  const handleQueryParamChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setQueryParam((prev) => ({
      ...prev,
      [name]: value,
    }))
  }

  useEffect(() => {
    loadData(pageNumber, pageSize)
  }, [pageNumber, pageSize])

  const handleReset = () => {
    setQueryParam(initialFormData)
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setPageNumber(page)
    setPageSize(pageSize)
  }
  return {
    loadData,
    loading,
    pageNumber,
    pageSize,
    queryParam,
    total,
    dataList,
    setPageNumber,
    setPageSize,
    setQueryParam,
    handleQueryParamChange,
    handleReset,
    handlePageChange,
  }
}

export default useDataList
